import os
import sys
import zipfile
import shutil
import time

version = "0.Alpha"
file = None
folder = None
name = None
config = None

## Builds Package
def mkPackage(folder,package):
	zf = zipfile.ZipFile(package, "w")
	for dirname, subdirs, files in os.walk(folder):
		zf.write(dirname)
		for filename in files:
			zf.write(os.path.join(dirname, filename))
	zf.close()
## Appends Package
def adPackage(file,package):
	zf = zipfile.ZipFile(package, "a" )
	zf.write(file)
## Unpacks Package
def unPackage(package,folder):
	zip = zipfile.ZipFile(package)
	zip.extractall(folder)

## Procecess arguments
args = sys.argv
i = 0
loop = True
while loop == True:
	try:
		if args[i] == "-f":
			file = args[next]
		if args[i] == "-F":
			folder = args[next]
		if args[i] == "-n":
			name = args[next]
		if args[i] == "-c":
			config = args[next]
		if args[i] == "-x":
			config = args[next]
		i += 1
	except:
		loop = False
	next = i + 1

## Preflight check
print("Starting...")
error = []
greenLight = True
if file != None:
	if folder != None:
		greenLight = False
		error.append("Cannot specify both a file and a folder")
if name == None:
	greenLight = False
	error.append("No package name was specified")
if config == None:
	greenLight = False
	error.append("No configuration was specified")

## Start of the build
if greenLight == True:
	if file != None:
		if os.path.isfile(file):
			print("\t[*] Building " + name)
			tmpFolder = str(round(time.time()))
			os.makedirs(tmpFolder)
			shutil.copy2(file,tmpFolder)
			shutil.copy2(config,tmpFolder + "/label.xml")
			mkPackage(tmpFolder,name + ".package")
			shutil.rmtree(tmpFolder)
		else:
			error.append("'" + file + "' is not a file")
	if folder != None:
		if os.path.isdir(folder):
			print("\t[*] Building " + name)
			tmpFolder = str(round(time.time()))
			shutil.copytree(folder,tmpFolder)
			shutil.copy2(config,tmpFolder + "/label.xml")
			mkPackage(tmpFolder,name + ".package")
			shutil.rmtree(tmpFolder)
		else:
			error.append("'" + folder + "' is not a folder")
if not error == []:
	for i in error:
		print("\t[!] " + i)

## Done!
print("...Done")